/*
 * @Author: shijianxin
 * @Date: 2022-04-08 17:07:54
 * @Description: 小方块组合类
 */

import { Square } from "./Square";
import { Point, Shape } from "./types";

export class SquareGroup {
  private readonly _squares: Square[] = [];

  // 获取所有小方块坐标
  public get squares(): Square[] {
    return this._squares;
  }

  // 获取小方块形状坐标
  public get shape(): Shape {
    return this._shape;
  }

  // 获取中心点坐标
  public get centerPoint(): Point {
    return this._centerPoint;
  }

  // 设置中心点 同时设置所有小方块的坐标
  public set centerPoint(v: Point) {
    this._centerPoint = v;
    // 同时设置所有小方块坐标
    this.setSquarePoints();
  }

  /**
   * 根据中心点的坐标，以及形状，设置每个小方块的坐标
   */
  private setSquarePoints() {
    this._shape.forEach((p, i) => {
      this._squares[i].point = {
        x: this._centerPoint.x + p.x,
        y: this._centerPoint.y + p.y,
      };
    });
  }

  /**
   * 判断旋转的方向是否为顺时针
   */
  protected isClock = true; // 子类中可修改

  constructor(
    private _shape: Shape,
    private _centerPoint: Point,
    private _color: string
  ) {
    // 设置小方块数组的坐标
    const arr: Square[] = [];
    this._shape.forEach((p) => {
      const sq = new Square();
      sq.color = this._color;
      arr.push(sq);
    });
    this._squares = arr;
    this.setSquarePoints();
  }

  /**
   * 得到旋转之后的坐标
   */
  afterRotateShape(): Shape {
    if (this.isClock) {
      return this._shape.map((p) => {
        const newP: Point = {
          x: -p.y,
          y: p.x,
        };
        return newP;
      });
    } else {
      return this._shape.map((p) => {
        const newP: Point = {
          x: p.y,
          y: -p.x,
        };
        return newP;
      });
    }
  }

  /**
   * 旋转
   */
  rotate(): void {
    const newShape = this.afterRotateShape();
    this._shape = newShape;
    this.setSquarePoints();
  }
}
